package bjtu.cit.bookshop.controller.admin;

import bjtu.cit.bookshop.common.ErrorCode;
import bjtu.cit.bookshop.controller.BaseController;
import bjtu.cit.bookshop.entities.User;
import bjtu.cit.bookshop.service.IUserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created by jia19 on 2015/10/12.
 */
@Controller
@RequestMapping("/admin/")
public class UserController extends BaseController {

    @Resource
    private IUserService userService = null;

    @RequestMapping("user.do")
    public String book(HttpSession session, HttpServletRequest request, ModelMap model) {
        String loginName = checkAdminLogin(session);
        if (loginName == null) {
            return "/admin/index";
        }
        model.addAttribute("isLogin", true);
        model.addAttribute("loginName", loginName);
        model.addAttribute("current", "user");

        List<User> userList = userService.getUserList();
        model.addAttribute("userList", userList);

        return "admin/user";
    }

    @RequestMapping("userEdit.do")
    public String userEdit(HttpSession session, HttpServletRequest request, ModelMap model) {
        String loginName = checkAdminLogin(session);
        if (loginName == null) {
            return "/admin/index";
        }

        model.addAttribute("isLogin", true);
        model.addAttribute("loginName", loginName);
        model.addAttribute("current", "user");

        String id = request.getParameter("id");
        if (id == null) {
            return "admin/badParameter";
        }

        try {
            User user = userService.getUserById(Integer.valueOf(id));
            model.addAttribute("user", user);
        } catch (Exception e) {
            e.printStackTrace();
            return "admin/badParameter";
        }

        return "admin/userEdit";
    }

    @RequestMapping("saveUser.do")
    @ResponseBody
    public ErrorCode saveUser(HttpSession session, HttpServletRequest request) {

        return SUCCESS;
    }

}
